import json
import re

from django import http
from django.contrib.auth import login, authenticate, logout
from django.db import DatabaseError
from django.urls import reverse
from django_redis import get_redis_connection

from carts.utils import merge_cart_cookie_to_redis
from goods.models import SKU
from meiduo_mall.utils.response_code import RETCODE
from meiduo_mall.utils.views import LoginRequiredMinxin, LoginRequiredJSONMixin
from .models import User, Address
from django.shortcuts import render, redirect

# Create your views here.

from django.views import View
import logging

logger = logging.getLogger('django')


class UserBrowseHistory(LoginRequiredJSONMixin, View):
    #登录过以后才可以访问

    def get(self, request):
        '''
        获取浏览记录
        :param request:
        :return:
        '''
        # 1.链接redis
        redis_conn = get_redis_connection('history')

        # 2.获取所有的商品id: skus_ids
        skus_ids = redis_conn.lrange('history_%s' % request.user.id, 0, -1)


        skus = []
        # 3.遍历, 获取每一个商品id
        for sku_id in skus_ids:

            # 4.取出对应的商品
            sku = SKU.objects.get(id=sku_id)

            # 5.拼接格, 保存到list
            skus.append({
                'id':sku.id,
                'name':sku.name,
                'default_image_url':sku.default_image_url,
                'price':sku.price
            })

        # 6.返回
        return http.JsonResponse({'code':RETCODE.OK,
                                  'errmsg':'ok',
                                  'skus':skus})

    def post(self, request):
        '''
        用户的浏览记录保存接口
        :param request:
        :return:
        '''
        # 1. 接受参数(json)
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        # 2. 校验参数
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('sku_id不存在')

        # 3. 链接redis, 创建 pl
        redis_conn = get_redis_connection('history')
        pl = redis_conn.pipeline()
        user = request.user

        # 4. 去重  保存 截取
        pl.lrem('history_%s' % user.id, 0, sku_id)#把里面的商品全部删除
        pl.lpush('history_%s' % user.id, sku_id)#再存储
        pl.ltrim('history_%s' % user.id, 0, 4)#再截取，界面上保留5个

        # 5. 执行pl
        pl.execute()

        # 6. 返回
        return http.JsonResponse({'code': RETCODE.OK,
                                  'errmsg': 'ok'})


class ChangePasswordView(LoginRequiredJSONMixin,View):

    """修改密码"""
    def get(self,request):
        """展示修改密码界面"""
        return render(request,'user_center_pass.html')


    def post(self,request):
        '''修改密码业务逻辑'''
        #1.接收参数
        old_password=request.POST.get('old_password')
        new_password=request.POST.get('new_password')
        new_password2=request.POST.get('new_password2')
        #2.校验参数
        if not all([old_password,new_password,new_password2]):
            return http.HttpResponseForbidden('缺少必传参数')
        try:

            request.user.check_password(old_password)
        except Exception as e:
            logger.error(e)
            return render(request, 'user_center_pass.html', {'origin_pwd_errmsg': '原始密码错误'})
        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return http.HttpResponseForbidden('密码最少8位，最长20位')
        if new_password != new_password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')
        try:
            #修改密码
            request.user.set_password(new_password2)
            request.user.save()
        except Exception as e:
            logger.error(e)
            return render(request, 'user_center_pass.html', {'change_pwd_errmsg': '修改密码失败'})

        #清理状态保持信息
        logout(request)
        response=redirect(reverse('users:login'))
        response.delete_cookie('username')

        #返回
        return response


class UpdateTitleAddressView(LoginRequiredJSONMixin,View):
    '''设置地址标题'''
    def put(self,request,address_id):
        #接收参数：地址标题
        json_dict=json.loads(request.body.decode())
        title=json_dict.get('title')
        try:
            #查询地址
            address=Address.objects.get(id=address_id)

            #设置新的地址标题
            address.title=title
            address.save()
        except Exception as e:
            return http.JsonResponse({'code':RETCODE.DBERR,'errmsg':'设置地址标题失败'}
            )
        #响应删除地址结果
        return http.JsonResponse({'code':RETCODE.DBERR,'errmsg':'设置地址标题成功'})


class DefaultAddressView(LoginRequiredJSONMixin,View):
    '''设置默认地址'''
    def put(self,request,address_id):
        try:
            address=Address.objects.get(id=address_id)

            #设置地址为默认地址
            request.user.default_address=address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code':RETCODE.DBERR,'errmsg':'设置默认地址失败'})
        return http.JsonResponse({'code':RETCODE.DBERR,'errmsg':'设置默认地址成功'})
class UpdateDestroyAddressView(LoginRequiredJSONMixin,View):
    '''修改和删除地址'''

    def put(self,request,address_id):
        '''修改地址'''
        #1.接收参数
        json_dict=json.loads(request.body.decode())

        receiver=json_dict.get('receiver')
        province_id=json_dict.get('province_id')
        city_id=json_dict.get('city_id')
        district_id=json_dict.get('district_id')
        place=json_dict.get('place')
        mobile=json_dict.get('mobile')
        tel=json_dict.get('tel')
        email=json_dict.get('email')
        #2.校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')
        #3.判断地址是否存在，并更新地址信息
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code':RETCODE.DBERR,'errmsg':'更新地址失败'})

        #构造响应数据
        address=Address.objects.get(id=address_id)
        address_dict={
             "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email

        }

        #响应更新地址结果
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'OK',
                                  'address':address_dict})


    def delete(self,request,address_id):
        '''删除地址'''
        try:
            #查询要删除的地址
            address=Address.objects.get(id=address_id)
            #将地址逻辑删除设置为True
            address.is_deleted=True
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code':RETCODE.DBERR,'errmsg':'删除地址失败'})


    #响应删除地址结果
        return http.JsonResponse({'code':RETCODE.DBERR,'errmsg':'删除地址成功！'})




class CreateAddressView(LoginRequiredJSONMixin, View):

    def post(self, request):
        '''
        增加用户的地址
        :param request:
        :return:
        '''
        # 1. 判断是否超过20个:
        count = request.user.addresses.model.objects.filter(is_deleted=False).count()
        # count1 = request.user.addresses.count()
        if count >= 20:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR,
                                      'errmsg': '地址个数超过20个'})

        # 2. 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 3. 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseForbidden('缺少必传参数')

        if not re.match(r'1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('手机号格式错误')

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')

        # 4. 保存(Address)
        try:
            address = Address.objects.create(
                user=request.user,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                title=receiver,
                receiver=receiver,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )

            # 5. 如果没有默认地址, 设置一下
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()
        except Exception as e:
            return http.JsonResponse({'code': RETCODE.DBERR,
                                      'errmsg': '数据库保存失败'})

        # 6. 拼接参数,返回
        address_dict = {
            'id': address.id,
            'title': address.title,
            'receiver': address.receiver,
            'province': address.province.name,
            'city': address.city.name,
            'district': address.district.name,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email
        }

        return http.JsonResponse({'code': RETCODE.OK,
                                  'errmsg': 'ok',
                                  'address': address_dict})

class AddressView(LoginRequiredMinxin, View):

        def get(self, request):
            '''
            返回用户地址界面
            :param request:
            :return:
            '''
            # 1. 获取当前用户的所有地址
            addresses = Address.objects.filter(user=request.user, is_deleted=False)

            address_dict_list = []

            # 2. 遍历所有地址,拿取每一个地址
            for address in addresses:
                # 3. 整理返回的数据格式
                address_dict = {
                    'id': address.id,
                    'title': address.title,
                    'receiver': address.receiver,
                    'province': address.province.name,
                    'city': address.city.name,
                    'district': address.district.name,
                    'place': address.place,
                    'mobile': address.mobile,
                    'tel': address.tel,
                    'email': address.email
                }
                # 4. 判断当前的地址是否是默认地址,
                # 如果是: 放到list的第一个,不是追加
                default_address = request.user.default_address
                if default_address.id == address.id:
                    # 放到list的第一个
                    address_dict_list.insert(0, address_dict)
                else:
                    address_dict_list.append(address_dict)

            # 5. 返回数据
            context = {
                'default_address_id': request.user.default_address_id,
                'addresses': address_dict_list
            }

            return render(request, 'user_center_site.html', context)

#
# class UserInfoView(LoginRequiredMinxin,View):
#     '''用户中心'''
#     def get(self,request):
#         '''提供个人信息界面'''
#
#
#         #若果使用该方法，它的用法如下：
#         # #进行判断：是否登录验证
#         # if request.user.is_authenticated():
#             #如果登录，，则正常加载用户中心界面
#         return render(request,'user_center_info.html')
#         # else:
#         #     #否则，进入登录界面，进行登录
#         #      return redirect(reverse('users:login'))
class VerifyEmailView(View):
    '''验证邮箱'''

    def get(self, request):
        '''
        实现邮箱验证逻辑
        :param request:
        :return:
        '''
        token = request.GET.get('token')

        # 校验参数：判断token是否为空和过期，提前user
        if not token:
            return http.HttpResponseForbidden('缺少token')
        # 调用上面封装好的方法，将token传入
        user = User.check_verify_email_token(token)
        if not user:
            return http.HttpResponseForbidden('无效的token')

        # 修改email_active的值为True
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError('激活邮件失败')

        return redirect(reverse('users:info'))


class EmailView(LoginRequiredJSONMixin, View):
    '''添加邮箱'''

    def put(self, request):
        ''''实现添加邮箱逻辑'''

        # 接收参数
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')
        # 校验参数
        if not email:
            return http.HttpResponseForbidden("确实email参数")
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.HttpResponseForbidden('参数email有误')
        # 赋值email字段
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '添加邮箱失败！'})

        # 导入：
        from celery_tasks.email.tasks import send_verify_email

        # 一步发送验证邮件
        verify_url = request.user.generate_verify_email_url()
        send_verify_email.delay(email, verify_url)
        # 响应添加邮箱结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': "添加邮箱成功！"})


class UserInfoView(LoginRequiredMinxin, View):
    '''用户中心'''

    def get(self, request):
        """提供个人信息界面"""

        # 将验证用户的信息进行拼接
        context = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active
        }
        return render(request, 'user_center_info.html', context)


class LogoutView(View):
    '''退出登录'''

    def get(self, request):
        # 清理session
        logout(request)
        # 退出登录，重定向到登录页
        response = redirect(reverse('contents:index'))
        # 由于首页中用户名是从cookie中读取的
        # 所以退出登录时，需要将cookie中用户名清除
        response.delete_cookie('username')
        # 返回响应
        return response


class LoginView(View):
    '''用户登录'''

    def get(self, request, ):

        '''
        提供登录界面的接口
        :param request:
        :return:
        '''
        # 返回登录界面
        return render(request, 'login.html')

    def post(self, request):
        '''
        实现登录逻辑
        :param username:
        :param password:
        :param remembered:
        :return:
        '''
        # 1.获取参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')
        # 2.校验参数
        # 2.1先判断参数是否齐全
        if not all([username, password]):
            return http.HttpResponseForbidden("缺少必传参数！")
            # 2.2判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('请输入正确的用户名和手机号！')
            # 2.3判断密码是否是8-20个字符
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('密码最少八位数，最长20位')
        # 3.获取登录用户，并看用户是否存在
        user = authenticate(username=username, password=password)  # 验证登录用户(其实就是拿前端获取到的用户信息取数据库看是否存在，如果不存在就提示异常）
        if user is None:
            return render(request, 'login.html', {"account_errmsg": "用户名或密码错误！"})
        # 4.实现状态保持
        login(request, user)
        # 4.1设置状态保持的周期
        if remembered != 'on':
            # 如果用户没有选中，就是不记住用户：浏览器回话结束就关闭即把session过期时间设置为0 ,浏览器关闭回话结束
            request.session.set_expiry(0)
        else:
            request.session.set_expiry(None)  # 不设置时间，NOne为默认，session默认过期时间为两周
            # #5.返回响应
            # return redirect(reverse('contents:index'))
            # 生成响应对象
        # response=redirect(reverse('contents:index'))

        next = request.GET.get('next')
        if next:
            response = redirect(next)  # next存在则根据next 取出info
        else:
            response = redirect(reverse('contents:index'))
        # 在响应对象中设置用户名信息
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)

        # 合并购物车
        response = merge_cart_cookie_to_redis(request, user,response )
        # 返回响应结果
        return response;





class MobileCountView(View):
    """判断手机号是否重复注册"""

    def get(self, request, mobile):
        '''

        :param request:
        :param mobile:
        :return:
        '''
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


class UsernameCountView(View):
    """判断用户是否重复注册"""

    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


class RegisterView(View):
    "用户注册"

    def get(self, request):
        "提供注册界面"
        return render(request, 'register.html')

    def post(selfs, request):
        "实现用户注册"
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        sms_code_client = request.POST.get('sms_code')
        allow = request.POST.get('allow')
        # 判断用户是否齐全
        if not all([username, password, password2, mobile, allow]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断用户是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden("请输入5-20个字符的用户名")
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20位的密码')
        # 判断两次密码是否一致
        if password != password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入正确的手机号码')
        # 判断是否勾选用户协议
        if allow != 'on':
            return http.HttpResponseForbidden('请勾选用户协议')

        # 对短信验证进行校验
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_code_%s' % mobile)
        if sms_code_server is None:
            return render(request, 'register.html', {'sms_code_errmsg': "验证码失效!!!!!ssd"})
        # 对比前端后端的验证码
        if sms_code_client.lower() != sms_code_server.decode().lower():
            return render(request, 'register.html', {'sms_code_errmsg': '无效的短信验证码'})
        # 保存到数据库

        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except DatabaseError:
            return render(request, 'register.html', {'sms_code_errmsg': '注册失败'})

        login(request, user)
        # 生成响应对象
        response = redirect(reverse('contents:index'))
        # 在相应对象中设置用户名信息
        # 将用户名写入到cookie，有效期15天
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)

        # 返回响应
        return response
        # return http.HttpResponse('注册成功，重定向到首页')
        # return redirect(reverse('contents:index'))
